package com.hinnotek.amoeba.ui.activity.old

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import com.lee.common.base.BaseActivity
import com.hinnotek.amoeba.R
import com.hinnotek.amoeba.base.BaseBean
import com.hinnotek.amoeba.bean.old.AmeobaCustomerListBean
import com.hinnotek.amoeba.bean.old.AmibaProjectListBean
import com.hinnotek.amoeba.bean.old.AmibaSysUserAdminBean
import com.hinnotek.amoeba.databinding.ActivityPaymentRequestAddAmoebaBinding
import com.hinnotek.amoeba.dialog.CustomDialog
import com.hinnotek.amoeba.ext.initAdapter
import com.hinnotek.amoeba.utilities.*
import com.hinnotek.amoeba.viewmodels.AmibaPayViewModel
import com.hinnotek.amoeba.viewmodels.PublicInterfaceViewModel
import com.lee.common.network.getRequestBody
import com.lee.common.network.net.ObserverState
import com.lee.common.utils.SharedPreUtils
import com.xuexiang.xutil.common.StringUtils

class PaymentRequestAddAmoebaActivity : BaseActivity<ActivityPaymentRequestAddAmoebaBinding>() {

    private var orgId = 0
    private var customerId = 0
    private var amibaCustomerProjectId = 0
    private var amibaProjectId = 0
    private var approvalUserId = 0
    private var orgName = ""

    private val viewModel by viewModels<PublicInterfaceViewModel>()
    private val payViewModel by viewModels<AmibaPayViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setLeftVisible(true)
        setTitle("添加付款申请")

        setContentView(R.layout.activity_payment_request_add_amoeba)
    }

    override fun initVew() {

        bindingView.rbPrP.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                bindingView.llChooseUnit.visibility = View.GONE
                bindingView.llPaymentChooseProject.visibility = View.GONE
                bindingView.llPaymentChoosePdProject.visibility = View.VISIBLE
            } else {
                bindingView.llChooseUnit.visibility = View.VISIBLE
                bindingView.llPaymentChooseProject.visibility = View.VISIBLE
                bindingView.llPaymentChoosePdProject.visibility = View.GONE
            }
        }
        bindingView.payLay.tvPaymentHopeDate.setOnClickListener { v: View? ->
            IntentUtils.startActivityForResult(
                this,
                MaterialDesignCalendarActivity::class.java,
                null,
                111
            )
        }
        bindingView.superButtonSubmit.setOnClickListener(View.OnClickListener { v: View? ->
            if (ClickUtil.isFastClick()) {
                return@OnClickListener
            }
            var provideProjectName = ""
            var customerName = ""
            var projectName = ""

            if (bindingView.rbPrP.isChecked) {
                provideProjectName =
                    bindingView.escPaymentChoosePdProject.editText.text.toString().trim()
                if (StringUtils.isEmpty(provideProjectName)) {
                    ToastUtils.show(mContext, "请选择项目")
                    return@OnClickListener
                }
            } else {
                customerName = bindingView.escPaymentChooseUnit.editText.text.toString().trim()
                if (StringUtils.isEmpty(customerName)) {
                    ToastUtils.show(mContext, "请选择签署单位")
                    return@OnClickListener
                }
                projectName = bindingView.escPaymentChooseProject.editText.text.toString().trim()
                if (StringUtils.isEmpty(projectName)) {
                    ToastUtils.show(mContext, "请选择项目")
                    return@OnClickListener
                }
            }
            val payDate: String =
                bindingView.payLay.tvPaymentHopeDate.getText().toString().trim()
            if (StringUtils.isEmpty(payDate)) {
                ToastUtils.show(mContext, "请选择期望付款日期")
                return@OnClickListener
            }
            val payOverview: String = bindingView.payLay.metPaymentCause.contentText.trim()
            if (StringUtils.isEmpty(payOverview)) {
                ToastUtils.show(mContext, "请填写付款事由")
                return@OnClickListener
            }
            val payTotal: String = bindingView.payLay.etPaymentTotal.text.toString().trim()
            if (StringUtils.isEmpty(payTotal)) {
                ToastUtils.show(mContext, "请填写付款总额")
                return@OnClickListener
            }
            val approvalUser: String =
                bindingView.payLay.escPaymentRelatedApprover.editText.getText().toString().trim()
            if (StringUtils.isEmpty(approvalUser)) {
                ToastUtils.show(mContext, "请选择关联审批人")
                return@OnClickListener
            }
            addAmibaPay(
                orgId,
                orgName,
                customerId,
                customerName,
                amibaCustomerProjectId,
                projectName,
                amibaProjectId,
                provideProjectName,
                payDate,
                payOverview,
                payTotal,
                approvalUserId,
                approvalUser,
                2,
                "宁创"
            )
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                111 -> bindingView.payLay.tvPaymentHopeDate.text = data?.getStringExtra("date")
            }
        }
    }

    override fun setData() {
        orgId = SharedPreUtils.getInteger("orgId", 0)
        orgName = SharedPreUtils.getString("orgName")

        viewModel.getAmibaProjectListByOrgId(orgId)
            .observe(this, object : ObserverState<MutableList<AmibaProjectListBean>>() {
                override fun onDataChange(data: MutableList<AmibaProjectListBean>) {
                    val strings = arrayOfNulls<String>(data.size)
                    data.forEachIndexed { index, amountAllocatedBean ->
                        strings[index] = amountAllocatedBean.projectName
                    }
                    bindingView.escPaymentChoosePdProject.initAdapter(strings)
                    bindingView.escPaymentChoosePdProject.setOnItemClickListener { parent, view, position, id ->
                        amibaProjectId = data[position].amibaProjectId
                    }
                    super.onDataChange(data)
                }

                override fun onError(msg: String?, code: Int) {
                    super.onError(msg, code)
                }
            })

        viewModel.getAmibaCustomerListByOrgId(orgId)
            .observe(this, object : ObserverState<MutableList<AmeobaCustomerListBean>>() {
                override fun onDataChange(data: MutableList<AmeobaCustomerListBean>) {
                    val strings = arrayOfNulls<String>(data.size)
                    data.forEachIndexed { index, amountAllocatedBean ->
                        strings[index] = amountAllocatedBean.customerName
                    }
                    bindingView.escPaymentChooseUnit.initAdapter(strings)
                    bindingView.escPaymentChooseUnit.setOnItemClickListener { _, _, position, id ->
                        amibaCustomerProjectId = data[position].customerId
                    }
                    super.onDataChange(data)
                }
            })


        viewModel.getAmibaSysUserAdminByOrgId(orgId)
            .observe(this, object : ObserverState<MutableList<AmibaSysUserAdminBean>>() {
                override fun onDataChange(data: MutableList<AmibaSysUserAdminBean>) {
                    val strings = arrayOfNulls<String>(data.size)
                    data.forEachIndexed { index, amountAllocatedBean ->
                        strings[index] = amountAllocatedBean.personName
                    }
                    bindingView.payLay.escPaymentRelatedApprover.initAdapter(strings)
                    bindingView.payLay.escPaymentRelatedApprover.setOnItemClickListener { _, _, position, id ->
                        approvalUserId = data[position].userId
                    }
                    super.onDataChange(data)
                }

                override fun onError(msg: String?, code: Int) {
                    super.onError(msg, code)
                }
            })
    }

    /**
     * app端添加阿米巴付款接口
     */
    private fun addAmibaPay(
        orgId: Int, orgName: String, customerId: Int, customerName: String,
        amibaCustomerProjectId: Int, projectName: String, amibaProjectId: Int,
        provideProjectName: String, payDate: String, payOverview: String,
        payTotal: String, approvalUserId: Int,
        approvalUser: String, sendUserId: Int, sendUser: String
    ) {

        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()

        val amibaPayType = if (bindingView.rbPrP.isChecked) 1 else 2
        val applyUserId = SharedPreUtils.getInteger("userId", 0)
        val createUser = SharedPreUtils.getString("personName")

        val map = mutableMapOf<String, Any>().apply {
            put("amibaPayType", amibaPayType)
            put("applyUserId", applyUserId)
            put("orgId", orgId)
            put("orgName", orgName)
            if (!bindingView.rbPrP.isChecked) {
                put("customerId", customerId)
                put("customerName", customerName)
                put("amibaCustomerProjectId", amibaCustomerProjectId)
                put("projectName", projectName)
            } else {
                put("amibaProjectId", amibaProjectId)
                put("provideProjectName", provideProjectName)
            }
            put("payDate", payDate)
            put("payOverview", payOverview)
            put("payTotal", payTotal)
            put("approvalUserId", approvalUserId)
            put("approvalUser", approvalUser)
            put("sendUserId", sendUserId)
            put("sendUser", sendUser)
            put("createUser", createUser)
        }

        payViewModel.addAmibaPay(getRequestBody(map)).observe(this,object : ObserverState<BaseBean>(){
            override fun onDataChange(data: BaseBean) {
                customDialog.dismiss()
                finishActivity()
                super.onDataChange(data)
            }

            override fun onError(msg: String?, code: Int) {
                customDialog.dismiss()
                ToastUtils.showShort(mContext, msg)
                super.onError(msg, code)
            }
        })
    }
}